package com.example.service.impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.*;
import com.example.mapper.LectureMapper;
import com.example.mapper.TeacherMapper;
import com.example.mapper.UserMapper;
import com.example.service.SignService;
import com.example.service.UserService;
import com.example.utils.UserVerifyHandler;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserVerifyHandler userVerifyHandler;
    @Autowired
    private LectureMapper lectureMapper;
    @Autowired
    private SignService signService;
    @Autowired
    private TeacherMapper teacherMapper;

    /*public Map<String,Object> importExcel(MultipartFile file) throws Exception{
        HashMap<String, Object> map = new HashMap<>();
        ImportParams importParams = new ImportParams();
        //表格标题行数,默认0
        importParams.setTitleRows(1);
        //是否需要校验上传的Excel
        importParams.setNeedVerify(true);
        //告诉easypoi我们自定义的验证器
//        importParams.setVerifyHandler(userVerifyHandler);
        List<Object> list = null;
        System.out.println(ExcelImportUtil.importExcelMore(file.getInputStream(), UserImportVO.class, importParams).getList());
//        ExcelImportResult<UserImportVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(),UserImportVO.class,importParams);
        List<User> collect = list.stream().map((item) -> {
            User user = new User();
            BeanUtil.copyProperties(item, user);
            return user;
        }).collect(Collectors.toList());
        map.put("userList",null);

        return map;
    }*/


    @Override
    public Map<String,Object> importExcel(MultipartFile file) throws Exception{
        HashMap<String, Object> map = new HashMap<>();
        String classCode = RandomUtil.randomString(8);

        map.put("userList","");

        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> generateClass(String className,String classPosition,String classTeacher,MultipartFile file) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        //获取sheet页的数量
        Workbook workBook = getWorkBook(file);
        int sheetNum = workBook.getNumberOfSheets();
        String sheetName = "";
        //标识导入的excel文件中是否存在多个班级信息 1 -是；0-否
        int continueImport = 1;

        for (int index = 0; index < sheetNum && continueImport==1; index++) {
            //当表格的sheet大于1时再进行课程名称的拼接
            if (sheetNum>1){
                sheetName = workBook.getSheetName(index);
            }

            String classCode = RandomUtil.randomString(8);
            Lecture lecture1 = new Lecture();
            lecture1.setClassCode(classCode);
            lecture1.setClassLocation(classPosition);
            /**
             * 在和前端的提示中，约定当存在多个班级信息时需要将sheet名称进行修改，否则无需修改
             *  如果识别到的sheet名称不包含She，则说明本次需要导入多个班级信息，需要获取不同sheet内的数据
             *  否则将continueImport修改为0，则表明只需获取默认第一个sheet内的数据
             */

            if (!sheetName.contains("She")){
                lecture1.setClassName(className+sheetName);
            }else {
                lecture1.setClassName(className);
                continueImport = 0;
            }

            lecture1.setClassTeacher(classTeacher);
            lectureMapper.insert(lecture1);
            ExcelAdapter(file, continueImport,classCode, index);



        }
        map.put("classCode",sheetNum);

        return map;
    }

    @Override
    public List selectLectureList() {
        LambdaQueryWrapper<Lecture> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Lecture::getId,Lecture::getClassName,Lecture::getClassCode,Lecture::getClassTeacher,Lecture::getClassLocation,Lecture::getCreateTime);

        List<Lecture> lectures = lectureMapper.selectList(wrapper);

        return lectures;
    }

    @Override
    public Map<String,Object> getLectureStudent(Long id) {
        HashMap<String, Object> map = new HashMap<>();
        String classCode = lectureMapper.selectById(id).getClassCode();
        List<User> list = this.lambdaQuery().eq(User::getClassCode, classCode)
                .select(User::getId, User::getUserName, User::getAccount, User::getClassCode).list();
        Sign newSignStatus = signService.getNewSignStatus(classCode);
        map.put("userList",list);
        map.put("signStatus",newSignStatus);
        return map;
    }

    @Override
    public Teacher teacherLogin(Teacher teacher) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getTeacherAccount,teacher.getTeacherAccount())
                        .eq(Teacher::getPassword,teacher.getPassword())
                .select(Teacher::getId,Teacher::getTeacherAccount,Teacher::getTeacherName);
        Teacher one = teacherMapper.selectOne(wrapper);
        if (!Objects.isNull(one)){
            return one;
        }

        return null;
    }

    @Override
    public Teacher teacherRegister(Teacher teacher) {
        HashMap<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getTeacherAccount,teacher.getTeacherAccount());
        Teacher one = teacherMapper.selectOne(wrapper);

        if (!Objects.isNull(one)){
            return one;
        }
        teacherMapper.insert(teacher);

        return null;

    }


    public List ExcelAdapter(MultipartFile file,int continueImport,String classCode,int index) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        //接收continueImport参数，判断是否需要获取不同sheet内的数据
        if (continueImport !=0){
            params.setStartSheetIndex(index);
        }

        List<User> collect = new ArrayList<>();
        try{
            List<UserImportVO> list = ExcelImportUtil.importExcel(file.getInputStream(), UserImportVO.class, params);
            if (list==null&&list.isEmpty()){
                return null;
            }
            list.stream().map((item) -> {
                User user = new User();
                BeanUtil.copyProperties(item, user);
                user.setClassCode(classCode);
                collect.add(user);
                return user;
            }).collect(Collectors.toList());
            this.saveBatch(collect);
        }catch (Exception e){

        }

        return collect;

    }

    //兼容excel的03和07版本
    public static Workbook getWorkBook(MultipartFile file) throws IOException {

        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        try {
            hssfWorkbook = new HSSFWorkbook(is);
        } catch (Exception ex) {
            is =file.getInputStream();
            hssfWorkbook = new XSSFWorkbook(is);
        }
        return hssfWorkbook;
    }

    @Override
    public List<User> getUserByClassCode(String classCode) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getClassCode, classCode);
        List<User> user = this.list(wrapper);
        return user;
    }

}
